package 序列化与反序列化工具;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-12-09
 * Time: 14:18
 */
import java.io.*;

public class ByteArrayUtil {

    // 将可序列化的对象转换为字节数组
    public static <T> byte[] oToB(T obj) {
        if (obj == null) {
            return null;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Serialization failed", e);
        }
    }

    // 将字节数组反序列化为对象
    public static Object bToO(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException("Deserialization failed", e);
        }
    }

    /*  测试代码 */
    public static void main(String[] args) {
        // 测试用例 1：基本对象序列化与反序列化
        String originalString = "Hello, world!";
        byte[] serializedString = ByteArrayUtil.oToB(originalString);
        Object deserializedString = ByteArrayUtil.bToO(serializedString);
        System.out.println("Test 1: " + deserializedString.equals(originalString)); // true

        // 测试用例 2：复杂对象的序列化与反序列化
        Person person = new Person("Alice", 30);
        byte[] serializedPerson = ByteArrayUtil.oToB(person);
        Person deserializedPerson = (Person) ByteArrayUtil.bToO(serializedPerson);
        System.out.println("Test 2: " + deserializedPerson); // Person{name='Alice', age=30}

        // 测试用例 3：空对象序列化
        byte[] serializedNull = ByteArrayUtil.oToB(null);
        Object deserializedNull = ByteArrayUtil.bToO(serializedNull);
        System.out.println("Test 3: " + (deserializedNull == null)); // true

        // 测试用例 4：无效字节数组反序列化
        try {
            byte[] invalidBytes = {0x00, 0x01};
            ByteArrayUtil.bToO(invalidBytes);
        } catch (RuntimeException e) {
            System.out.println("Test 4: Caught exception for invalid input: " + e.getMessage());
        }
    }
}

class Person implements Serializable {
    private static final long serialVersionUID = 1L; // 推荐添加 serialVersionUID 以确保序列化兼容性
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}


